package com.ukefu.util.ai;

import java.io.IOException;
import java.util.List;

import org.ansj.domain.Term;
import org.apache.commons.lang3.StringUtils;

import com.ukefu.webim.util.server.message.ChatMessage;
import com.ukefu.webim.web.model.AiUser;
import com.ukefu.webim.web.model.SysDic;
import com.ukefu.webim.web.model.UKeFuDic;

public class AiDic {
	
	private final AiDicTrie trie ;
	
	public AiDic(AiDicTrie trie){
		this.trie = trie ;
	}
	public String search(ChatMessage content, AiUser aiUser) throws IOException{
		return matchDic(content,DicSegment.nsegment(content.getMessage()) , aiUser) ;
	}
	
	
	private String matchDic(ChatMessage message,List<Term> content , AiUser aiUser) {
		String matchDic = null ;
		List<SysDic> dicList = UKeFuDic.getInstance().getDic("com.dic.xiaoe.input") ;
		boolean match = false ;
		StringBuffer expmsg = new StringBuffer();
		for(Term term : content) {
			expmsg.append(term.getName()).append("/").append(term.getNatureStr()).append("\r\n") ;
		}
		if(expmsg.length() > 0) {
			message.setExpmsg(expmsg.toString());
		}
		for(SysDic dic : dicList) {
			for(Term word : content) {
				if(!StringUtils.isBlank(dic.getDescription()) && (word.getName().matches(dic.getDescription()) || word.getNatureStr().toString().equals(dic.getDescription()))) {
					if(trie.search(dic.getId()) != null) {
						if(aiUser!=null && aiUser.getNames()!=null) {
							aiUser.getNames().put(dic.getCode(), word.getName()) ;
						}
						matchDic = trie.search(dic.getId()) ;
						match = true ; break ;
					}
				}
			}
			if(match) break ;
		}
		return matchDic;
	}
}
